package com.gui.client;

import com.gui.connect.Command;
import com.gui.connect.Connector;
import com.gui.connect.Processor;
import com.gui.connect.RedisReply;
import com.gui.exceptions.RedisConnectionException;
import com.gui.exceptions.RedisDataException;
import com.gui.util.Cmd;
import com.gui.util.ReplyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.IOException;

/**
 * Created by Gui on 2017/7/19.
 */
public class RedisClient implements Closeable {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    private String host = "localhost";
    private int port = 6379;
    private String password;

    private Connector connector;
    private Command command;
    private Processor processor;

    public RedisClient() {
    }

    public RedisClient(String host) {
        this.host = host;
    }

    public RedisClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public boolean connect() {
        connector = new Connector(host, port);
        connector.connect();
        command = connector.getCommand();
        processor = connector.getProcessor();

        //Auth
        if (password != null) {
            try {
                RedisReply reply = sendCmd(Cmd.AUTH, password);
                if (reply != null && reply.getType() == ReplyType.BULK) {
                    return true;
                }
                logger.info("验证成功");
            } catch (RedisDataException e) {
                logger.error(e.toString());
            }
        }
        return false;
    }

    public RedisReply sendCmd(Cmd cmd, Object... args) {
        String[] strs = new String[args.length];
        for (int i = 0; i < args.length; i ++) {
            strs[i] = String.valueOf(args[i]);
        }
        command.sendCmd(cmd, strs);
        try {
            return processor.getObjectReply();
        } catch (IOException e) {
            logger.error(e.toString());
        }
        return null;
    }

    public void setPassword(String password) {  this.password = password;   }

    public String getPassword() {   return password;    }

    @Override
    public void close() throws IOException {
        connector.close();
    }
}
